package com.gtpickupapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class SportResults extends Activity{

final List<Integer> eventIDS = new ArrayList<Integer>();
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 setContentView(R.layout.sportresults);
		 
		 Bundle bundle = getIntent().getExtras();
		 Log.e("start", bundle.getString("start"));
		 Log.e("end", bundle.getString("end"));
		 Log.e("sport", bundle.getString("sport"));
		 
		String result = "";
		InputStream is = null;
		String uname = bundle.getString("uName");//username.getText().toString();
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("userName" ,uname));
		nameValuePairs.add(new BasicNameValuePair("startDate" ,bundle.getString("start")));
		nameValuePairs.add(new BasicNameValuePair("endDate" ,bundle.getString("end")));
		nameValuePairs.add(new BasicNameValuePair("type" ,bundle.getString("sport")));
		
		
			//http post
			try{
					
			        HttpClient httpclient = new DefaultHttpClient();
			        HttpPost httppost = new HttpPost("http://gtplay.webatu.com/sportSearch.php");
			        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			        HttpResponse response = httpclient.execute(httppost);
			        HttpEntity entity = response.getEntity();
			        is = entity.getContent();
			}catch(Exception e){
			        Log.e("log_tag", "Error in http connection "+e.toString());
			}
			
			//convert response to string
			try{
			        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			        StringBuilder sb = new StringBuilder();
			        String line = null;
			        while ((line = reader.readLine()) != null) {
			                sb.append(line + "\n");
			        }
			        is.close();
			 
			        result=sb.toString();
			}catch(Exception e){
			        Log.e("log_tag", "Error converting result "+e.toString());
			}
			 
			//parse json data
			try{
					JSONArray jArray = new JSONArray(result);
					/* Find Tablelayout defined in main.xml */
			        TableLayout tl = (TableLayout)findViewById(R.id.sportresultsdisplay);
			        final Bundle bundle2 = new Bundle();
			        for(int i=0;i<jArray.length();i++){			        	
			        	JSONObject json_data = jArray.getJSONObject(i);
			        	eventIDS.add(json_data.getInt("EventID"));
			        	
			        	  
				             /* Create a new row to be added. */
				             TableRow tr = new TableRow(this);
				             tr.setLayoutParams(new LayoutParams(
				                            LayoutParams.FILL_PARENT,
				                            LayoutParams.WRAP_CONTENT));
				             
				             	  /*Create a textView for the name of the event */
				             	TextView text = new TextView(this);
				             	text.setText(json_data.getString("Name"));
				             	text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
				             	
				             	/*create a textView for the Date of the event*/
				             	TextView date = new TextView(this);
				             	date.setText(json_data.getString("Date"));
				             	date.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
				             	date.setPadding(20, 25, 20, 25);
				             	//date.setPadding(left, top, right, bottom)
				                  /* Create a Button to be the row-content. */
				                  Button b = new Button(this);
				                  b.setText("View");
				                  b.setId(i);
				                  
				                  b.setLayoutParams(new LayoutParams(
				                		  LayoutParams.WRAP_CONTENT,
				                            LayoutParams.WRAP_CONTENT));
				                  b.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
				      	          b.setOnClickListener(new View.OnClickListener() {
				      	        	public void onClick(View v) {
				      	        		Bundle bundle = getIntent().getExtras();
				      	        		bundle.putInt("eventID", eventIDS.get(v.getId()));
				      	        		Intent myintent = new Intent(SportResults.this, SportExpand.class);
				      	        		myintent.putExtras(bundle);
				      	        		
				      	        		View view = SearchEventsGroup.group.getLocalActivityManager().startActivity("show expand weight",myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
				      	        		
				      	        		SearchEventsGroup.group.replaceView(view);
				      	        		
				      	        	}         
				      	        });
				                  /* Add Button to row. */
				                  tr.addView(text);
				                  tr.addView(date);
				                  tr.addView(b);
				        /* Add row to TableLayout. */
				        tl.addView(tr,new TableLayout.LayoutParams(
				                  LayoutParams.FILL_PARENT,
				                  LayoutParams.WRAP_CONTENT));
			        	
			        }
			   
			        
			        
			}
			catch(JSONException e){
					showNoResults();
			        Log.e("log_tag", "Error parsing data "+e.toString());
			}
		 
		 
		 
		 
	}
	
	public void showNoResults(){
		TableLayout tl = (TableLayout)findViewById(R.id.sportresultsdisplay);
		 /* Create a new row to be added. */
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        
        /*Create a textView for the name of the event */
     	TextView text = new TextView(this);
     	text.setText("Sorry no results match your criteria, please expand your search");
     	text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
     	
     	 /* Add text to row. */
        tr.addView(text);
        
        /* Add row to TableLayout. */
        tl.addView(tr,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        
	}
	
}
